
package com.jojoteamwork.photo.ui;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jojoteamwork.photo.R;
import com.jojoteamwork.photo.provider.Model;
import com.jojoteamwork.photo.util.ImageCache;
import com.jojoteamwork.photo.util.ImageCache.ImageCacheParams;
import com.jojoteamwork.photo.util.ImageWorker;
import com.jojoteamwork.photo.util.ImageZipLoader;
import com.jojoteamwork.photo.util.Utils;
import com.jojoteamwork.photo.util.ZipDataReader;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import java.lang.reflect.Type;
import java.util.ArrayList;

public class ModelDetailActivity extends FragmentActivity {

    private TextView tvNumber;

    private ViewPager mPager;

    private int totalNum;

    // private TextView tvNowpoint;

    private Button btnPrev;

    private Button btnNext;

    private ProgressDialog progressDialog;

    private static final int MSG_GET_POINT_RETURN = 0;

    private static final int MSG_SAVE_PHOTO = 1;

    protected static final int MSG_NOT_ENOUGH = 2;

    protected static final int MSG_GET_POINT = 3;

    protected static final int MSG_UPDATE_POINT_ERROR = 4;

    private static final String IMAGE_CACHE_DIR = "cover";

    private String mFilename;

    public ImageWorker mImageWorker;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail_main);
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        mFilename = intent.getStringExtra("filename");
        if (TextUtils.isEmpty(mFilename)) {
            finish();
            return;
        }
        mPager = (ViewPager) findViewById(R.id.pager);
        btnPrev = (Button) findViewById(R.id.btnPrev);

        btnNext = (Button) findViewById(R.id.btnNext);
        tvNumber = (TextView) findViewById(R.id.movieNum);

        String modelsDescription = ZipDataReader.getText(Utils.MAGAZINE_DIR + "/" + mFilename,
                "models");

        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<Model>>() {
        }.getType();
        ArrayList<Model> models = gson.fromJson(modelsDescription, type);
        totalNum = models.size();
        ModelPagerAdapter adapter = new ModelPagerAdapter(getSupportFragmentManager(), models);
        mPager.setAdapter(adapter);
        // int movieId = getIntent().getIntExtra("movieId", -1);

        // if (movieId != -1) {
        // currentPosition = dbHelper.getMoviePosition(movieId);
        // }
        // appConnect = UUAppConnect.getInstance(this);
        // handler.sendEmptyMessage(MSG_GET_POINT);
        // mPager.setCurrentItem(currentPosition);
        tvNumber.setText(1 + "/" + totalNum);
        mPager.setOnPageChangeListener(changeListener);
        // LinearLayout container = (LinearLayout) findViewById(R.id.ad_layout);
        // UUAppConnect.getInstance(this).showBanner(container, 20);

        setNextPrevVisibility(0);
        findViewById(R.id.btnHome).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mImageWorker = new ImageZipLoader(this);
        ImageCacheParams cacheParams = new ImageCacheParams(IMAGE_CACHE_DIR);
        cacheParams.diskCacheEnabled = false;
        cacheParams.memCacheSize = 1024 * 1024 * Utils.getMemoryClass(this) / 3;
        mImageWorker.setImageCache(ImageCache.findOrCreateCache(this, cacheParams));
    }

    public ImageWorker getImageWorker() {
        return mImageWorker;
    }

    private void setNextPrevVisibility(int position) {
        if (position <= 0) {
            btnPrev.setVisibility(View.INVISIBLE);
        } else {
            btnPrev.setVisibility(View.VISIBLE);
        }
        if (position >= totalNum - 1) {
            btnNext.setVisibility(View.INVISIBLE);
        } else {
            btnNext.setVisibility(View.VISIBLE);
        }

    }

    OnPageChangeListener changeListener = new OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            tvNumber.setText((position + 1) + "/" + totalNum);
            setNextPrevVisibility(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public class ModelPagerAdapter extends FragmentStatePagerAdapter {

        public ModelPagerAdapter(FragmentManager fm, ArrayList<Model> models) {
            super(fm);
            mModels = models;
        }

        ArrayList<Model> mModels;

        @Override
        public int getCount() {
            return mModels.size();
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            final ModelDetailFragment fragment = (ModelDetailFragment) object;
            // As the item gets destroyed we try and cancel any existing work.
            fragment.cancelWork();
            super.destroyItem(container, position, object);
        }

        @Override
        public Fragment getItem(int position) {
            Model model = mModels.get(position);
            return ModelDetailFragment.newInstance(model, mFilename);
        }
    }

    // private void showLoadingDialog() {
    // progressDialog = new ProgressDialog(ModelDetailActivity.this);
    // progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    // progressDialog.setMessage(getText(R.string.loading));
    // progressDialog.setIndeterminate(true);
    // progressDialog.setCanceledOnTouchOutside(false);
    // progressDialog.show();
    // }

    // private void savePhoto(final Model model) {
    // if (!dbHelper.isCost(model.id)) {
    // new AlertDialog.Builder(this).setMessage(R.string.save_message)
    // .setTitle(R.string.save_title)
    // .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
    // {
    //
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // dialog.dismiss();
    // }
    // }).setPositiveButton(R.string.confirm, new
    // DialogInterface.OnClickListener() {
    //
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // showLoadingDialog();
    // Message msg = new Message();
    // msg.what = MSG_SAVE_PHOTO;
    // msg.obj = model;
    // handler.sendMessage(msg);
    //
    // }
    // }).show();
    // } else {
    // checkAndOpenPhoto(model, new SavePhotoNotifier(ModelDetailActivity.this,
    // model));
    // }
    //
    // }

    /**
     * 保存写真集到SD卡的回调函数
     * 
     * @author benoit
     */
    // class SavePhotoNotifier implements UpdatePointListener {
    // Context mContext;
    //
    // Model model;
    //
    // SavePhotoNotifier(Context context, Model model) {
    // mContext = context;
    // this.model = model;
    // }
    //
    // @Override
    // public void onError(String arg0) {
    // handler.sendEmptyMessage(MSG_UPDATE_POINT_ERROR);
    // }
    //
    // @Override
    // public void onSuccess(String arg0, int arg1) {
    // handler.sendEmptyMessage(MSG_GET_POINT);
    // Message msg = new Message();
    // msg.what = MSG_SAVE_PHOTO;
    // msg.obj = model;
    // handler.sendMessage(msg);
    //
    // }
    //
    // }

    // class OpenPhotoNotifier implements UpdatePointListener {
    // Context mContext;
    //
    // Model model;
    //
    // OpenPhotoNotifier(Context context, Model model) {
    // mContext = context;
    // this.model = model;
    // }
    //
    // @Override
    // public void onError(String arg0) {
    // handler.sendEmptyMessage(MSG_UPDATE_POINT_ERROR);
    // }
    //
    // @Override
    // public void onSuccess(String arg0, int arg1) {
    // handler.sendEmptyMessage(MSG_GET_POINT);
    // // openPhotoActivity(model);
    // }
    //
    // }

}
